package com.quasar.hpatient.view.record;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.custommodel.TemperatureTableItem;
import com.quasar.hpatient.model.httpmodel.AnotherResult;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.medicalmodel.DailyRecordDetailsData;
import com.quasar.hpatient.onInterface.OndailyRecordListener;
import com.quasar.hpatient.presenter.DailyRecordPresenter;
import com.quasar.hpatient.utils.OutliersValues;
import com.quasar.hpatient.utils.StringUtils;
import com.quasar.hpatient.view.adapter.TemperatureAdapter;
import com.quasar.hpatient.widget.SeekBarEditWidget;
import com.quasar.hpatient.widget.WidgetDateAdd;
import com.quasar.hpatient.widget.WidgetTime;
import com.quasar.hpatient.widget.lineChartView;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OptionsItem;
import org.androidannotations.annotations.OptionsMenu;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 体温记录
 */
@OptionsMenu(R.menu.menu_preservation)
@EActivity(R.layout.activity_temperature)
public class TemperatureActivity extends BaseActivity implements OndailyRecordListener {


    private TemperatureAdapter temperatureAdapter;
    private DailyRecordPresenter dailyRecordPresenter;

    //防止二次提交
    boolean isClick = true;

    @ViewById(R.id.main_toolbar)
    Toolbar main_toolbar;
    @ViewById(R.id.rv_list)
    RecyclerView rv_list;
    @ViewById(R.id.wd_dataAdd)
    WidgetDateAdd wd_dataAdd;
    //时间
    @ViewById(R.id.wt_time)
    WidgetTime wt_time;
    @ViewById(R.id.sw_detect)
    SeekBarEditWidget sw_detect;
    //折线图
    @ViewById(R.id.lc_post_list)
    lineChartView lc_post_list;

    @Extra
    String TimeVal;//其他跳转过来的时间

    @AfterViews
    void init() {
        initView();
        initData();
    }

    @Override
    protected void initView() {
        initToolbar();
        rv_list.setLayoutManager(new LinearLayoutManager(this));
        rv_list.setHasFixedSize(true);
        rv_list.setNestedScrollingEnabled(false);
        //隐藏日期按钮
        wd_dataAdd.hideViewDate();
        if (TimeVal != null && TimeVal.length() > 0) {
            wd_dataAdd.setTimeDate(TimeVal);
        }

        sw_detect.onClickTextView(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edittText(null);
            }
        });
    }

    @Override
    protected void initData() {

        dailyRecordPresenter = new DailyRecordPresenter(this);
        OneDayDailyRecord();
    }

    //初始化adapter布局
    public void initAdapter(List<TemperatureTableItem> data) {
        temperatureAdapter = new TemperatureAdapter(data);
        rv_list.setAdapter(temperatureAdapter);
        temperatureAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {

                    case R.id.tv_val:
                        if (temperatureAdapter.getData().get(position).getStats() != null) {
                            TemperatureTableItem temperatureTableItem = temperatureAdapter.getData().get(position);
                            edittText(temperatureTableItem);
                        }
                        break;
                }
            }
        });

        temperatureAdapter.setOnItemChildLongClickListener(new BaseQuickAdapter.OnItemChildLongClickListener() {
            @Override
            public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_val:
                        if (temperatureAdapter.getData().get(position).getStats() != null) {
                            TemperatureTableItem temperatureTableItem = temperatureAdapter.getData().get(position);
                            dialogdelete(temperatureTableItem);
                        }
                        break;
                }
                return true;
            }
        });
    }


    public void dialogdelete(final TemperatureTableItem temperatureTableItem) {

        Dialog.Builder builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {
                super.onPositiveActionClicked(fragment);
                deleteLongClick(temperatureTableItem.getId());
            }

            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {
                super.onNegativeActionClicked(fragment);
            }
        };
        builder.title("确认删除检测项吗？")
                .positiveAction("确定")
                .negativeAction("取消");
        ((SimpleDialog.Builder) builder).message("检测值可以帮助医生更准确的了解你的情况");
        DialogFragment fragment = DialogFragment.newInstance(builder);

        if (this instanceof AppCompatActivity) {
            AppCompatActivity activity = this;
            fragment.show(activity.getSupportFragmentManager(), null);
        }
    }


    public void deleteLongClick(String itemId) {
        dailyRecordPresenter.updateAloneItemDailyRecordDetail(itemId, "", "", "", ConstantManger.DELETEDAILY, "", "");
    }

    //保存
    boolean isUpdate=true;
    @OptionsItem(R.id.action_preservation)
    public void action_preservation() {

        ViseLog.d("检测值是否进行了修改"+sw_detect.updateVal());
        if(isUpdate){
            if(!sw_detect.updateVal()){
                msg("请修改检测值");
                return;
            }
        }


        final String Value = sw_detect.getDetectVal();//检测值
        String Time = wt_time.getTime();//检测时间
        String Date = wd_dataAdd.getDataTime();//检测日期
        final StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(Date);
        stringBuffer.append(" " + Time + ":00");

        if (isClick) {
            showDialog();
            isClick = false;
            dailyRecordPresenter.AddDailyRecordDetailData(
                    Value, stringBuffer.toString(),
                    "",
                    "",
                    ConstantManger.TEMPERATURENAME,
                    ConstantManger.COMPANYNAME, abnormalVal(Value));
        }
        isUpdate=true;
    }

    //检测值判断
    public String abnormalVal(String timeVal) {
        String warn = "";
        try {
            int stats = OutliersValues.TiWencrisisVal(Float.parseFloat(timeVal));
            if (stats != 0) {
                warn = "1";
            } else {
                warn = "0";
            }
        } catch (Exception e) {
            msg("检测值异常");
        }
        return warn;
    }

    @Override
    public void onDailyRecordDetailsSuccess(AnotherResult<DailyRecordDetailsData> data) {

        List<TemperatureTableItem> temperatureTableItemList = new ArrayList<>();
        TemperatureTableItem tableItem = new TemperatureTableItem();
        if (data.getList().size() != 0) {
            tableItem.setItemType(TemperatureTableItem.HEAD);
            tableItem.setDailyitemName("状态");
            tableItem.setDailyitemDose("摄氏度(℃)");
            temperatureTableItemList.add(tableItem);
        }
        for (int i = 0; i < data.getList().size(); i++) {
            TemperatureTableItem temperatureTableItem = new TemperatureTableItem();
            temperatureTableItem.setId(data.getList().get(i).getId() + "");
            temperatureTableItem.setLogTime(data.getList().get(i).getLogTime().substring(5, 16));
            temperatureTableItem.setLogValue(data.getList().get(i).getLogValue());
            temperatureTableItem.setDailyitemDose(data.getList().get(i).getDailyitemDose());
            temperatureTableItem.setDailyitemName(data.getList().get(i).getDailyitemName());
            temperatureTableItem.setItemType(TemperatureTableItem.BODY);
            temperatureTableItem.setReferenceValue(ConstantManger.TEMPERATURREFERENCE);//参考值
            temperatureTableItem.setIndexId(data.getList().get(i).getIndexId());
            temperatureTableItem.setStats(OutliersValues.TiWencrisisVal(Float.parseFloat(data.getList().get(i).getLogValue())) + "");
            temperatureTableItemList.add(temperatureTableItem);
        }
        initAdapter(temperatureTableItemList);
        int[] index = {0, 6};//截取字符串
        lc_post_list.setFlashback(temperatureTableItemList, index);
        isClick = true;
        dessDialog();

    }

    @Override
    public void onError(String msg) {
        if (msg != null) {
            msg(msg);
        }
        isClick = true;
        dessDialog();
    }

    public void dessDialog() {
        if (pd != null) {
            pd.dismiss();
        }
    }

    @Override
    public void onRefreshUI() {
        temperatureAdapter.notifyDataSetChanged();
        isClick = true;
        dessDialog();
    }

    //提交日常检查项成功
    @Override
    public void onSubmitSuccess(DataStateResult dataStateResult) {
        if (dataStateResult.getMsgCode().equals("0x00000000")) {
            msg("操作成功");
            sw_detect.defaultVal("365");
            OneDayDailyRecord();
        }
        isClick = true;
        dessDialog();
    }


    private final double temperatureMin = 30.0;
    private final double temperatureMax = 45.0;

    public void edittText(final TemperatureTableItem temperatureTableItem) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请输体温检测值");
        View views = LayoutInflater.from(this).inflate(R.layout.dialog_edit_detection, null);
        builder.setView(views);
        final EditText edit_min = (EditText) views.findViewById(R.id.edit_detection);
        edit_min.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)});

        edit_min.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                edit_min.setSelection(s.length());
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                int selectionStart = edit_min.getSelectionStart();
                int selectionEnd = edit_min.getSelectionEnd();

                if (s.toString() != null && s.toString().length() > 0) {
                    if (OutliersValues.editTextNum(s.toString())) {
                        //体温保留一位小数
                        float val = Float.parseFloat(s.toString());
                        TextColer(edit_min, OutliersValues.TiWencrisisVal(val));
                        ViseLog.d("验证数字" + StringUtils.isOnlyPointNumber(s.toString(), 1));
                        if (!StringUtils.isOnlyPointNumber(s.toString(), 1)) {
                            s.delete(selectionStart - 1, selectionEnd);
                            edit_min.setText(s);
                            edit_min.setSelection(s.length());
                        }
                    }
                }

                if (s.toString().trim().substring(0).equals(".")) {
                    edit_min.setText("0" + s);
                    edit_min.setSelection(2);
                }
            }
        });

        StringBuffer stringBuffer=new StringBuffer();
        if (temperatureTableItem != null) {
            edit_min.setText(temperatureTableItem.getLogValue());
            stringBuffer.append("确定");
        }else{
            stringBuffer.append("提交");
        }

        builder.setPositiveButton(stringBuffer.toString(), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                String val = edit_min.getText().toString();
                if(val==null || val.length()==0){
                    msg("检测值不能为空");
                }
                String Temperature = "";

                if (temperatureTableItem != null) {
                    if (val.length() != 0) {
                        double douval = Double.parseDouble(val);
                        if (temperatureMin <= douval && douval <= temperatureMax) {
                            Temperature = douval + "";
                            //异常值判断
                            dailyRecordPresenter.updateAloneItemDailyRecordDetail(temperatureTableItem.getId() + "",
                                    Temperature, "", "", ConstantManger.UPDATEDAILY, abnormalVal(Temperature), temperatureTableItem.getIndexId() + "");
                        } else {
                            testVal(edit_min, temperatureTableItem);
                        }
                    } else {
                        testVal(edit_min, temperatureTableItem);
                    }
                } else {
                    if (val.length() != 0) {
                        double douval = Double.parseDouble(val);
                        if (temperatureMin <= douval && douval <= temperatureMax) {
                            sw_detect.EditTextView(val);
                            //提交
                            isUpdate=false;
                            action_preservation();
                        }else{
                            msg("检测值为不可能值");
                        }
                    }

                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                showKeyboard(edit_min);
            }
        }, 300);
        builder.show();

    }

    public void showKeyboard(EditText editText) {
        if (editText != null) {
            //设置可获得焦点
            editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            //请求获得焦点
            editText.requestFocus();
            //调用系统输入法
            InputMethodManager inputManager = (InputMethodManager) editText
                    .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(editText, 0);
        }
    }

    public void testVal(EditText editText, TemperatureTableItem temperatureTableItem) {
        msg("检测值为不可能值");
        editText.setText(temperatureTableItem.getLogValue());


    }

    public void TextColer(EditText textView, int color) {

        if (color == 0) {
            textView.setTextColor(color(R.color.btcolor));
        } else {
            textView.setTextColor(color(R.color.red));
        }
    }

    private int color(int value) {
        return MainAppliaction.getInstance().getResources().getColor(value);
    }


    //修改
    @Override
    public void onUpdateValueSuccess(DataStateResult dataStateResult) {

        if (dataStateResult.getMsgCode().equals("0x00000000")) {
            OneDayDailyRecord();
        }
    }

    //删除
    @Override
    public void onDeleteValueSuccess(DataStateResult dataStateResult) {
        if (dataStateResult.getMsgCode().equals("0x00000000")) {
            //获取显示的日期
            OneDayDailyRecord();
        }
    }

    public void OneDayDailyRecord() {
        final String type = "7";
        String Time = wd_dataAdd.getDataTime();
        dailyRecordPresenter.GetUserOneDayDailyRecordData(ConstantManger.TEMPERATURENAME, Time, type);
    }
}
